package com.blyat.xsoft.kernel.component.pool;

import org.apache.commons.pool2.ObjectPool;

import java.lang.reflect.Proxy;

/**
 * @Auther: syh
 * @Date: 2020/8/3
 * @Description:
 */
public class ConnectionWrapping {
    public static <T extends Connection> T wrapConnection(T connection, ObjectPool<T> pool) {

        ConnectionInvokeHandler<T> handler = new ConnectionInvokeHandler<>(pool, connection);

        Class<?>[] implementedInterfaces = connection.getClass().getInterfaces();
        Class[] interfaces = new Class[implementedInterfaces.length + 1];
        interfaces[0] = HasTargetConnection.class;
        System.arraycopy(implementedInterfaces, 0, interfaces, 1, implementedInterfaces.length);

        T proxiedConnection = (T) Proxy.newProxyInstance(connection.getClass().getClassLoader(), interfaces, handler);
        handler.setProxyConnection(proxiedConnection);

        return proxiedConnection;
    }

    interface HasTargetConnection extends Connection {
        Connection getTargetConnection();
    }
}
